﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DiskFactory : MonoBehaviour {
    GameObject prefabDisk;
    HashSet<GameObject> freeSet, usedSet;

    void Awake() {
        prefabDisk = Resources.Load<GameObject>("Prefabs/Disk");
        if (prefabDisk == null) {
            Debug.LogError("prefabDisk is null");
        }
        freeSet = new HashSet<GameObject>();
        usedSet = new HashSet<GameObject>();
    }
    public GameObject GetDisk() {
        GameObject ret = null;
        if (freeSet.Count > 0) {
            HashSet<GameObject>.Enumerator et = freeSet.GetEnumerator();
            if (!et.MoveNext()) {
                return null;
            }
            ret = et.Current;
            freeSet.Remove(ret);
            ret.SetActive(true);
        }
        else {
            ret = Instantiate(prefabDisk);
        }
        usedSet.Add(ret);
        return ret;
    }
    public void FreeDisk(GameObject obj) {
        if (!usedSet.Contains(obj)) {
            throw new System.InvalidOperationException("Cannot free this object");
        }
        obj.SetActive(false);
        usedSet.Remove(obj);
        freeSet.Add(obj);
    }
}
